package tree.huffman;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 构建 Huffman 树
 * @Auther Jun jie Yi
 * @Date 11:14 2021/7/20
 */
public class HuffmanTree {
    public static void main(String[] args) {
        int[] arr = {10, 4, 5, 6, 23, 44};
        Node root = createHuffmanTree(arr);
        System.out.println("哈夫曼树前序遍历结果为：");
        preOrder(root);
    }

    //创建Huffman的方法
    public static Node createHuffmanTree(int[] arr) {
        //遍历数组，并将数组每个元素变为Node类型，并且放入顺序表中
        List<Node> nodes = new ArrayList<>();
        for (int i : arr) {
            nodes.add(new HuffmanTree().new Node(i));
        }
        while (nodes.size() > 1) {
            //从小到大排序
            Collections.sort(nodes);
            //取出节点权值最小的两个节点构成二叉树
            Node leftNode = nodes.get(0);
            Node rightNode = nodes.get(1);
            //重新构建新的二叉树，以之前两个节点为左右子节点
            Node parent = new  HuffmanTree().new Node(leftNode.value + rightNode.value);
            parent.left = leftNode;
            parent.right = rightNode;
            //删除两个子节点，并将父节点放入顺序表中
            nodes.remove(leftNode);
            nodes.remove(rightNode);
            nodes.add(parent);
        }
        return nodes.get(0);
    }

    //实现前序遍历
    public static void preOrder(Node root) {
        if(root == null) return;
        System.out.println(root);
        if(root.left != null) preOrder(root.left);
        if(root.right != null) preOrder(root.right);
    }

    //创建结点的类
    class Node implements Comparable<Node> {
        int value;//结点权值
        Node left;
        Node right;
        public Node(int value) {
            this.value = value;
        }

        @Override
        public int compareTo(Node o) {
            //表示从小到大排序
            return this.value - o.value;
        }

        @Override
        public String toString() {
            return "Node{" + "value=" + value + '}';
        }
    }
}
